<template>
  <div class="form-menu-list">
    <div class="form-menu-list-body">
      <div style="margin-bottom: 10px">
        <a-button @click="addNew" shape="round" type="primary" icon="plus">新建</a-button>
        <a-button style="margin-left: 5px" shape="round" @click="copy" icon="copy">复制</a-button>
      </div>
      <HTable ref="table" select="single" @selectChange="selectChange" :columns="columns" :configurable="false"
              :dataSource="menus" :pagination="false">
        <template slot="action" slot-scope="text, record, index">
          <a @click.stop="() => remove(record)">删除</a>
        </template>
      </HTable>
      <FormMenuModal @ok="FormMenuModalOK" ref="FormMenuModal"/>
    </div>
  </div>
</template>
<script>
import HTable from '@/components/hhd/design/HTable/HTable.vue';
import {createModelForVue, createProps, guid} from '@/utils';
import FormMenuModal from '@/components/hhd/design/FormMenu/FormMenuModal.vue';

export default {
  name: 'FormMenuList',
  components: {FormMenuModal, HTable},
  model: createModelForVue('selectedMenu'),
  props: {
    selectedMenu: createProps(Object, () => undefined),
    menus: createProps(Array),
  },
  data() {
    return {
      columns,
    };
  },
  methods: {
    addNew() {
      this.$refs.FormMenuModal.open();
    },
    FormMenuModalOK(menu) {
      this.menus.push(menu);
      this.$emit('change', menu);
      this.$refs.table.setSelectedRowKeys([menu.id]);
    },
    remove(record) {
      this.$confirm({
        title: '确定删除吗?',
        content: '删除后不可恢复, 确定删除吗?',
        okText: '确定',
        cancelText: '取消',
        onOk: () => {
          let index = this.menus.findIndex(r => r.id === record.id);
          if (index !== -1) {
            this.menus.splice(index, 1);
          }
          if (this.selectedMenu && this.selectedMenu.id === record.id) {
            this.$emit('change', undefined);
          }
        }
      });
    },
    copy() {
      if (!this.selectedMenu) {
        this.$message.error('请选中一条');
        return;
      }
      let newMenu = JSON.parse(JSON.stringify(this.selectedMenu));
      newMenu.id = guid();
      newMenu.menuName += '(副本)';
      this.menus.push(newMenu);
    },
    selectChange({selectRows}) {
      if (selectRows && selectRows.length) {
        this.$emit('change', selectRows[0]);
      } else {
        this.$emit('change', undefined);
      }
    },
  },
  watch: {
    selectedMenu: {
      handler() {
        if (!this.selectedMenu) {
          this.$refs.table && this.$refs.table.clearSelection()
        }
      },
      immediate: true,
    }
  }
};

const columns = [
  {
    title: '业务列表',
    dataIndex: 'menuName',
  }
];
</script>
<style>
.form-menu-list {
  width: 600px;
  height: 100%;
  overflow: auto;
  padding: 10px;
}

.form-menu-list-body {
  background: white;
  height: 100%;
  padding: 10px;
  border: 1px solid #e2e4e9;
}
</style>